class PopupController {
  constructor() {
    this.terminals = [];
    this.currentTab = null;
    this.init();
  }

  async init() {
    await this.getCurrentTab();
    await this.loadTerminals();
    this.setupEventListeners();
    this.setupMessageListener();
  }

  async getCurrentTab() {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    this.currentTab = tab;
  }

  async loadTerminals() {
    try {
      const response = await chrome.tabs.sendMessage(this.currentTab.id, {
        type: 'GET_TERMINALS'
      });
      
      this.terminals = response || [];
      this.renderTerminals();
      this.updateStatus();
    } catch (error) {
      this.updateStatus('未检测到终端或页面不支持', 'error');
    }
  }

  renderTerminals() {
    const container = document.getElementById('terminals-container');
    container.innerHTML = '';

    if (this.terminals.length === 0) {
      container.innerHTML = '<p>未检测到终端</p>';
      return;
    }

    this.terminals.forEach(terminalId => {
      const terminalDiv = document.createElement('div');
      terminalDiv.className = 'terminal-item';
      terminalDiv.innerHTML = `
        <h4>终端: ${terminalId}</h4>
        <input type="text" class="command-input" placeholder="输入命令..." data-terminal="${terminalId}">
        <button class="send-btn" data-terminal="${terminalId}">发送</button>
        <div class="output-area" id="output-${terminalId}"></div>
      `;
      container.appendChild(terminalDiv);
    });
  }

  setupEventListeners() {
    // 发送命令按钮
    document.addEventListener('click', async (e) => {
      if (e.target.classList.contains('send-btn')) {
        const terminalId = e.target.dataset.terminal;
        const input = document.querySelector(`input[data-terminal="${terminalId}"]`);
        const command = input.value.trim();
        
        if (command) {
          await this.sendCommand(terminalId, command);
          input.value = '';
        }
      }
      
      // 快速命令按钮
      if (e.target.classList.contains('auto-command-btn')) {
        const command = e.target.dataset.command;
        if (this.terminals.length > 0) {
          await this.sendCommand(this.terminals[0], command);
        }
      }
    });

    // 回车发送命令
    document.addEventListener('keypress', async (e) => {
      if (e.key === 'Enter' && e.target.classList.contains('command-input')) {
        const terminalId = e.target.dataset.terminal;
        const command = e.target.value.trim();
        
        if (command) {
          await this.sendCommand(terminalId, command);
          e.target.value = '';
        }
      }
    });

    // 刷新按钮
    document.addEventListener('click', async (e) => {
      if (e.target.id === 'refresh-btn') {
        await this.loadTerminals();
      }
    });
  }

  async sendCommand(terminalId, command) {
    try {
      const response = await chrome.tabs.sendMessage(this.currentTab.id, {
        type: 'SEND_COMMAND',
        terminalId: terminalId,
        command: command
      });

      if (response && response.success) {
        this.updateStatus(`命令已发送: ${command}`, 'success');
        this.addToOutput(terminalId, `> ${command}`);
      } else {
        this.updateStatus('发送命令失败', 'error');
      }
    } catch (error) {
      this.updateStatus('发送命令时出错', 'error');
    }
  }

  setupMessageListener() {
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      if (request.type === 'OUTPUT_ANALYSIS') {
        this.displayAnalysis(request.data);
      }
    });
  }

  displayAnalysis(analysis) {
    const analysisOutput = document.getElementById('analysis-output');
    const analysisContent = document.getElementById('analysis-content');
    
    analysisOutput.style.display = 'block';
    
    const analysisItem = document.createElement('div');
    analysisItem.innerHTML = `
      <div><strong>时间:</strong> ${new Date(analysis.timestamp).toLocaleTimeString()}</div>
      <div><strong>终端:</strong> ${analysis.terminalId}</div>
      <div><strong>检测到的模式:</strong> ${analysis.patterns.join(', ') || '无'}</div>
      ${analysis.nextAction ? `<div><strong>自动执行:</strong> ${analysis.nextAction}</div>` : ''}
      <hr>
    `;
    
    analysisContent.insertBefore(analysisItem, analysisContent.firstChild);
    
    // 限制显示的分析记录数量
    while (analysisContent.children.length > 10) {
      analysisContent.removeChild(analysisContent.lastChild);
    }
  }

  addToOutput(terminalId, text) {
    const outputDiv = document.getElementById(`output-${terminalId}`);
    if (outputDiv) {
      const line = document.createElement('div');
      line.textContent = text;
      outputDiv.appendChild(line);
      outputDiv.scrollTop = outputDiv.scrollHeight;
    }
  }

  updateStatus(message = '', type = 'success') {
    const statusDiv = document.getElementById('status');
    
    if (!message) {
      message = this.terminals.length > 0 
        ? `检测到 ${this.terminals.length} 个终端` 
        : '未检测到终端';
    }
    
    statusDiv.textContent = message;
    statusDiv.className = `status ${type}`;
  }
}

// 初始化popup控制器
document.addEventListener('DOMContentLoaded', () => {
  new PopupController();
});